/**
 * Copyright (C) 2011 Taobao Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.taobao.jaket;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Xueqiang Mi
 */
final class Anchors {
    private Map<String, Pair> anchors = new HashMap<String, Pair>();

    public boolean containsKey(String key) {
        return anchors.containsKey(key);
    }

    public Pair get(String key) {
        return anchors.get(key);
    }

    public void put(String key, int head, int tail) {
        Pair pair = new Pair(head, tail);
        anchors.put(key, pair);
    }

    /**
     * update the index after do inserting operation
     * 
     * @param position
     * @param offset
     */
    public void update(int position, int offset) {
        for (Pair pair : anchors.values()) {
            if (pair.getHead() >= position) {
                pair.move(offset);
            } else if (pair.getTail() >= position) {
                pair.moveTail(offset);
            }
        }
    }
}

final class Pair {
    private int head;
    private int tail;

    public Pair(int head, int tail) {
        this.head = head;
        this.tail = tail;
    }

    public int getHead() {
        return head;
    }

    public int getTail() {
        return tail;
    }

    public void move(int step) {
        head += step;
        tail += step;
    }

    public void moveTail(int step) {
        tail += step;
    }

    public void setHead(int head) {
        this.head = head;
    }

    public void setTail(int tail) {
        this.tail = tail;
    }

    @Override
    public String toString() {
        return "Pair [head=" + head + ", tail=" + tail + "]";
    }
}
